<template>
  <div class="update-photo">
   <img :src="img" class="img" ref="img">
   <div class="toolbat">
    <div class="cancel" @click="$emit('close')">取消</div>
    <div class="confirm" @click="onConfirm">完成</div>
   </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updataUserPhoto } from '@/api/user'
export default {
  name: 'UpdatePhoto',
  props: {
    img: {
      type: [String, Object],
      require: true
    }
  },
  data () {
    return {
      cropper: null
    }
  },

  mounted () {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1, // 裁纸器的裁剪模式 为1就是只能在画布中移动
      dragMode: 'move', // crop是拖动框 move是拖动画布
      aspectRatio: 1, // 截图比例
      autoCropArea: 1, // 自动截取
      cropBoxMovable: false, // 截图区是否可以移动
      cropBoxResizable: false, // 截图区是否可以缩放
      background: false, // 背景
      movable: true // 画布是否可以移动
    })
  },

  methods: {
    onConfirm () {
      this.cropper.getCroppedCanvas().toBlob(blob => {
        this.updateUserPhoto(blob)

        // })
      })
    },
    async updateUserPhoto (blob) {
      this.$toast.loading({
        message: '保存中...',
        forbidClick: true, // 禁用背景点击
        duration: 0 // 如果为0，则持续展示

      })
      try {
        // 如果接口 Content-Type要求application/json则传递普通json对象
        // updataUserPhoto({
        //   photo: blob
        // })
        // 如果接口 Content-Type要求multipart/form-data 则必须穿fromdataa对象
        const fromData = new FormData()
        fromData.append('photo', blob)
        const { data } = await updataUserPhoto(fromData)
        // 关闭弹出层
        this.$emit('close')
        // 更新视图
        this.$emit('update-photo', data.data.photo)
        this.$toast.success('上传成功')
      } catch (error) {
        this.$toast.fail('上传失败')
      }
    }
  }
}
</script>

<style lang="less" scoped>
.update-photo {
  background-color: #000;
  height: 100%;
  .toolbat {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    .cancel, .confirm {
      width: 45px;
      height: 45px;
      font-size: 20px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
    }
  }
}
.img {
  display: block;
 max-width: 100%;
}
</style>
